package com.isman.placeslist;

import java.util.Calendar;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isman.placeslist.apiobject.Session;
import com.isman.placeslist.apiobject.SingUp;
import com.isman.placeslist.util.InputValidator;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Spinner;
import android.widget.Toast;

public class PageSingup extends Activity {
	private static final int DATE_DIALOG_ID = 0;
	private static final int IMAGE_CHOINE = 1;
	private static final int GALLERY_ACTIVITY = 0;
	private static final int CAMERA_ACTIVITY = 1;
	private static final int CONFIRM_ACTIVITY = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_singup);

		vEtFiestname = (EditText) findViewById(R.id.et_singup_firstname);
		vEtLastname = (EditText) findViewById(R.id.et_singup_lastname);
		vEtEmail = (EditText) findViewById(R.id.et_singup_email);
		vEtTelephone = (EditText) findViewById(R.id.et_singup_telephone);
		vEtBirthday = (EditText) findViewById(R.id.et_singup_birthday);
		vSpGender = (Spinner) findViewById(R.id.sp_singup_gender);
		vImgPhoto = (ImageView) findViewById(R.id.img_singup_photo);
		vBtnClose = (Button) findViewById(R.id.btn_singup_close);
		vBtnSingup = (Button) findViewById(R.id.btn_singup_singup);

		vBtnClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mImageUri = null;
				mFilePath = "";
				vImgPhoto.setImageDrawable(getResources().getDrawable(
						R.drawable.ic_menu_invite));
				vImgPhoto.setScaleType(ScaleType.CENTER);
				vBtnClose.setVisibility(View.GONE);
			}
		});
		vBtnSingup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSingup();
			}
		});
		vEtBirthday.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean arg1) {
				if (arg1) {
					showDialog(DATE_DIALOG_ID);
				}
			}
		});
		vEtBirthday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		vImgPhoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(IMAGE_CHOINE);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case GALLERY_ACTIVITY:
				mImageUri = data.getData();
				mFilePath = mGetPath(mImageUri);

				vImgPhoto.setImageURI(mImageUri);
				vImgPhoto.setScaleType(ScaleType.FIT_CENTER);
				vBtnClose.setVisibility(View.VISIBLE);
				break;
			case CAMERA_ACTIVITY:
				mFilePath = mGetPath(mImageUri);

				vImgPhoto.setImageURI(mImageUri);
				vImgPhoto.setScaleType(ScaleType.FIT_CENTER);
				vBtnClose.setVisibility(View.VISIBLE);
				break;
			case CONFIRM_ACTIVITY:
				SingUp singup = (SingUp) data.getExtras().getSerializable(
						PageConfirm.SINGUP_INFO);
				mSingupWithEmail(singup);
				break;
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		case IMAGE_CHOINE:
			final CharSequence[] imgChoine = { "Choine from Gallery",
					"Capture a Image" };
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Upload image.");
			builder.setItems(imgChoine, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					if (item == 0) {
						mGallery();
					} else {
						mCapture();
					}
				}
			});
			return builder.create();

		}
		return null;
	}

	protected void mSingup() {
		String firstname = vEtFiestname.getText().toString();
		String lastname = vEtLastname.getText().toString();
		String email = vEtEmail.getText().toString();
		String telephone = vEtTelephone.getText().toString();
		String birthday = vEtBirthday.getText().toString();
		String gender = String.valueOf(vSpGender.getSelectedItemPosition());

		boolean InFirst = InputValidator.checkName(firstname);
		boolean InLast = InputValidator.checkName(lastname);
		boolean InEmail = InputValidator.checkEmailorTelephone(email);
		boolean InTel = InputValidator.checkTelephone(telephone);
		boolean InBirth = InputValidator.checkDate(birthday);

		if (!InFirst) {
			vEtFiestname.setError(getResources().getString(
					R.string.lbl_name_tip));
		}
		if (!InLast) {
			vEtLastname.setError(getResources()
					.getString(R.string.lbl_name_tip));
		}
		if (!InEmail) {
			vEtEmail.setError(getResources().getString(R.string.lbl_email_tip));
		}
		if (!InTel) {
			vEtTelephone.setError(getResources().getString(
					R.string.lbl_telephone_tip));
		}
		if (!InBirth) {
			vEtBirthday.setError(getResources().getString(
					R.string.lbl_birthday_tip));
		}

		if (!InFirst || !InLast || !InEmail || !InTel || !InBirth) {
			return;
		} else {
			SingUp singup = new SingUp();
			singup.setFirstname(firstname);
			singup.setLastname(lastname);
			singup.setBirthday(birthday);
			singup.setEmail(email);
			singup.setGender(gender);
			singup.setTelephone(telephone);
			singup.setFromWith(SingUp.FROM_WITH_EMAIL);

			mCheckEmail(singup);
		}
	}

	protected void mCheckEmail(final SingUp singup) {
		mDialog = ProgressDialog.show(PageSingup.this, "", "Loading...");
		ServiceProvider provider = new ServiceProvider(PageSingup.this);
		provider.CheckEmail(vEtEmail.getText().toString(),
				new AsyncRunnerHeadler() {
					@Override
					public void onError(int statusCode, final String json) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mDialog.cancel();
								Toast.makeText(getApplicationContext(),
										"Error " + json, Toast.LENGTH_LONG)
										.show();
							}
						});
					}

					@Override
					public void onConnectingError(final String message) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mDialog.cancel();
								Toast.makeText(getApplicationContext(),
										"ConnectingError " + message,
										Toast.LENGTH_LONG).show();
							}
						});
					}

					@Override
					public void onComplete(final String json) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mDialog.cancel();
								boolean result = Boolean.parseBoolean(json
										.trim());
								if (result) {
									Intent intent = new Intent(PageSingup.this,
											PageConfirm.class);
									intent.putExtra(PageConfirm.SINGUP_INFO,
											singup);
									startActivityForResult(intent,
											CONFIRM_ACTIVITY);
								} else {
									Toast.makeText(getApplicationContext(),
											result + " Complete " + json,
											Toast.LENGTH_LONG).show();
								}
							}
						});
					}

					@Override
					public void onAuthenticate(final String json) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mDialog.cancel();
								Toast.makeText(getApplicationContext(),
										"onAuthenticate" + json,
										Toast.LENGTH_LONG).show();
							}
						});
					}
				});
	}

	protected void mSingupWithEmail(SingUp singup) {
		mDialog = ProgressDialog.show(PageSingup.this, "", "Singing Up");
		ServiceProvider provider = new ServiceProvider(PageSingup.this);
		provider.SingUpWithEmail(singup, new AsyncRunnerHeadler() {
			@Override
			public void onError(final int statusCode, final String json) {
				mDialog.cancel();
				Toast.makeText(PageSingup.this,
						"Error " + statusCode + "  " + json, Toast.LENGTH_LONG)
						.show();
			}

			@Override
			public void onConnectingError(final String json) {
				mDialog.cancel();
				Toast.makeText(PageSingup.this, "ConnectingError" + json,
						Toast.LENGTH_LONG).show();
			}

			@Override
			public void onComplete(final String json) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mDialog.cancel();
						Intent intent = new Intent();
						try {
							Session singin = new Gson().fromJson(json,
									Session.class);
							intent.putExtra(PageMain.SINGIN_INFO, singin);
						} catch (JsonSyntaxException e) {
							e.printStackTrace();
						}
						setResult(Activity.RESULT_OK, intent);
						finish();
					}
				});
			}

			@Override
			public void onAuthenticate(final String json) {
				mDialog.cancel();
				Toast.makeText(PageSingup.this, "Authenticate " + json,
						Toast.LENGTH_LONG).show();
			}
		});
	}

	protected void mCapture() {
		String fileName = "temp.jpg";
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.TITLE, fileName);
		mImageUri = getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
		startActivityForResult(intent, CAMERA_ACTIVITY);
	}

	protected void mGallery() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"),
				GALLERY_ACTIVITY);
	}

	protected String mGetPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			vEtBirthday.setText(mDay + "/" + (mMonth + 1) + "/" + mYear);
		}
	};
	private final Calendar c = Calendar.getInstance();
	private int mYear = c.get(Calendar.YEAR);
	private int mMonth = c.get(Calendar.MONTH);
	private int mDay = c.get(Calendar.DAY_OF_MONTH);
	private Uri mImageUri;
	private String mFilePath = "";
	private ProgressDialog mDialog;

	private EditText vEtFiestname;
	private EditText vEtLastname;
	private EditText vEtEmail;
	private EditText vEtTelephone;
	private EditText vEtBirthday;
	private Spinner vSpGender;
	private ImageView vImgPhoto;
	private Button vBtnClose;
	private Button vBtnSingup;

}
